package com.yihu.yihuds.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.article.beans.UserQuery;
import com.yihu.beans.dic.DatadicQuery;
import com.yihu.beans.dic.Resource;
import com.yihu.cms.action.BaseController;
import com.yihu.cms.service.DataDictionaryService;
import com.yihu.cms.service.UserService;
import com.yihu.cms.service.WexinMsgByGroupService;
import com.yihu.cms.util.HttpUtils;
import com.yihu.cms.util.Osslog;
import com.yihu.web.bean.RedPack;
import com.yihu.web.bean.UserBehavior;
import com.yihu.web.bean.ViewPointStatis;
import com.yihu.web.bean.user.Address;
import com.yihu.web.bean.user.Coupon;
import com.yihu.web.bean.user.User;
import com.yihu.web.bean.user.Wallet;
import com.yihu.web.bean.user.WechatLoginStat;
import com.yihu.web.bean.vo.AddressQuery;
import com.yihu.web.bean.vo.CouponRebateQuery;
import com.yihu.web.bean.vo.RedpackQuery;
import com.yihu.web.bean.vo.RewardQuery;
import com.yihu.web.bean.vo.UserBehaviorQuery;
import com.yihu.web.bean.vo.UserPublishQuery;
import com.yihu.web.bean.vo.UsersQuery;
import com.yihu.web.bean.vo.ViewPointStatisQuery;
import com.yihu.web.bean.vo.WechatLoginStatQuery;
import com.yihu.web.constats.DSConstants;
import com.yihu.web.constats.ResponseVO;
import com.yihu.web.utils.FormatDateTime;
import com.yihu.web.utils.InfoHelp;
import com.yihu.web.utils.PropertiesUtil;
import com.yihu.yihuds.service.YihuUserService;

/***
 * 用户地址管理
 * 
 * @author Aaron
 *
 */
@Controller
public class UserYihuController extends BaseController {
	YihuUserService service = new YihuUserService();

	// 新增地址
	@RequestMapping(value = "/user/address", method = RequestMethod.POST)
	public @ResponseBody Object addAddress(@RequestBody Address address) {
		return service.addAddress(address);
	}

	// 获取地址列表
	@RequestMapping(value = "/user/addressList", method = RequestMethod.GET)
	public @ResponseBody Object getAllAddress(AddressQuery query) {
		return service.getAllAddressByUser(query);
	}

	// 获取地所有系统用户
	@RequestMapping(value = "/user/sys", method = RequestMethod.GET)
	public @ResponseBody Object getAllSysUsers(UserPublishQuery query) {
		query.setModel(0);
		return service.getOpenidsByQuery(query);
	}

	// 更新地址
	@RequestMapping(value = "/user/update", method = RequestMethod.POST)
	public @ResponseBody Object updateUser(@RequestBody User user) {
		System.out.println("in to /user/update:" + JSON.toJSONString(user));
		return service.updateUser(user);
	}

	// 更新地址
	@RequestMapping(value = "/user/address", method = RequestMethod.PUT)
	public @ResponseBody Object updateAddress(@RequestBody Address address) {
		return service.updateAddress(address);
	}

	// 根据TAG获取地址： 两个参数： USERID, TAG
	@RequestMapping(value = "/user/getAddress", method = RequestMethod.GET)
	public @ResponseBody Object getAddress(Address address) {
		return service.getAddress(address);
	}

	// 检查TAG是否存在： 两个参数： USERID, TAG ，0为不存在，可以新增，1为存在
	@RequestMapping(value = "/user/checkAddressTag", method = RequestMethod.GET)
	public @ResponseBody Object checkAddressTag(Address address) {
		return service.checkTag(address);
	}

	// 设置默认收货地址
	@RequestMapping(value = "/user/address/default", method = RequestMethod.POST)
	public @ResponseBody Object setDefaultAddress(@RequestBody Address address) {
		return service.setDefaultAddress(address);
	}

	// 设置默认收货地址
	@RequestMapping(value = "/user/address", method = RequestMethod.DELETE)
	public @ResponseBody Object deleteAddress(Address address) {
		return service.deleteAddress(address);
	}

	/***
	 * 创建用户钱包
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/user/wallet", method = RequestMethod.POST)
	public @ResponseBody Object wallet(@RequestBody Wallet wallet) {
		return service.wallet(wallet);
	}

	/***
	 * 查询用户profile
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/user/profile", method = RequestMethod.GET)
	public @ResponseBody Object getUserProfile(long userId) {
		// ..
		Map<String, Object> map = service.getUserProfile(userId);
		User user = (User) map.get("user");
		Map<String,Object> cutTimes = getCutTimes(user);
		map.put("cutTimes", cutTimes);
		return map;
	}

	private Map<String,Object> getCutTimes(User user) {
		Map<String,Object> result = new HashMap<String,Object>(); 
		try{
			DataDictionaryService service = new DataDictionaryService();
			DatadicQuery query = new DatadicQuery();
			int model = user.getModel();
			String level = user.getLevel();
			if(StringUtils.isBlank(level)){
				level = "lv0";
			}
			StringBuffer sb = new StringBuffer();
			sb.append("/cms/config/userlevel/"+level);
			if(model==DSConstants.USER_MODEL_NORMAL||model==DSConstants.USER_MODEL_SYSTEM){
				sb.append("/generaluser");
			}
			else {
				sb.append("/agentuser");
			}
			query.setParentPath(sb.toString());
			query.setKeyName("add");
			Resource r = service.getDicByPath(query);
			Osslog.info("cuttimes.Resource: "+r);
			long dicAdd = 38;
			long cutAdd = 0;
			if(r!=null){
				dicAdd = Long.parseLong(r.getValue());
			}
			query.setKeyName("assist");
			r = service.getDicByPath(query);
			Osslog.info("cuttimes.Resource: "+r);
			long dicAssist = 38;
			long cutAssist = 0;
			if(r!=null){
				dicAssist = Long.parseLong(r.getValue());
			}
			String timesurl = PropertiesUtil.getInstance().getProperty("cuturl")+"gettimes?userId="+user.getUserId();
			String json = HttpUtils.sendGet(timesurl);
			JSONObject jo = JSON.parseObject(json);
			if(jo.getLong("result").longValue()==0){
				JSONObject data = jo.getJSONObject("data");
				cutAdd = data.getLongValue("add");
				cutAssist = data.getLongValue("assist");
			}
			Osslog.info("profile.dicAdd: "+dicAdd+" cutAdd:"+cutAdd+" dicAssist:"+dicAssist+" cutAssist:"+cutAssist);
			long remainAdd = dicAdd - cutAdd;
			long remainAssist = dicAssist - cutAssist;
			result.put("dicAdd", dicAdd);
			result.put("dicAssist", dicAssist);
			result.put("remainAdd", remainAdd);
			result.put("remainAssist", remainAssist);
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}

	/***
	 * 查询用户的返利详情
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/user/rebate", method = RequestMethod.GET)
	public @ResponseBody Object getUserRebate(CouponRebateQuery query) {
		return service.getCouponRebateBy(query);
	}

	/***
	 * 查询用户钱包
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/user/wallet", method = RequestMethod.GET)
	public @ResponseBody Object getWallet(long userId) {
		return service.getWalletByUserId(userId);
	}

	/***
	 * 用户优惠券充值
	 * 
	 * @param user
	 * @return
	 *//*
		 * @RequestMapping(value = "/user/wallet/recharge1", method =
		 * RequestMethod.POST) public @ResponseBody Object
		 * recharge1(@RequestBody Wallet wallet) { return
		 * service.recharge(wallet); }
		 */

	/***
	 * 用户优惠券充值
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/user/wallet/recharge", method = RequestMethod.POST)
	public @ResponseBody Object recharge(@RequestBody Coupon coupon) {

		return service.recharge(coupon);
	}

	/***
	 * 用户返利充值
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/user/rebate/recharge", method = RequestMethod.POST)
	public @ResponseBody Object rebateRecharge(@RequestBody User user) {
		Osslog.debug("rebateRecharge: " + user);
		return service.rebateRecharge(user);
	}

	/***
	 * 购买商品后，减去已使用的金额
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/user/wallet/reduce", method = RequestMethod.POST)
	public @ResponseBody Object reduce(@RequestBody Wallet wallet) {
		return service.reduce(wallet);
	}

	/***
	 * 获取传播者的奖金详情列表
	 * 
	 * @param user
	 *            rid
	 * @return
	 */
	@RequestMapping(value = "/user/reward/list", method = RequestMethod.GET)
	public @ResponseBody Object getRewards(RewardQuery query) {
		return service.getRewardsOfUser(query);
	}

	/***
	 * 检查传播者奖金可以提现情况
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/user/reward/check", method = RequestMethod.GET)
	public @ResponseBody Object checkRewards() {
		return service.checkRewards();
	}

	/***
	 * 充值到账户余额 accountValue
	 * 
	 * @param userId:用户Id
	 *            payValue:充值的金额
	 * @return
	 */
	@RequestMapping(value = "/user/wallet/account/recharge", method = RequestMethod.POST)
	public @ResponseBody Object rechargeAcount(@RequestBody Wallet wallet) {
		return service.rechargeAcount(wallet);
	}

	/***
	 * 更新手机号码
	 * 
	 * @param userId:用户Id
	 *            moblieNumber:手机号码
	 * @return
	 */
	@RequestMapping(value = "/user/update/mobile", method = RequestMethod.POST)
	public @ResponseBody Object updateMobile(@RequestBody User user) {
		User u = new User();
		u.setUserId(user.getUserId());
		u.setMobileNumber(user.getMobileNumber());
		return service.updateUser(u);
	}

	/***
	 * 获取某一个产品所有访问人
	 * 
	 * @param pid:产品Id
	 * @param dateStr;
	 *            格式： yyyy-MM-dd，为空即为当天
	 * @param type:
	 *            模块名称
	 * @return
	 */
	@RequestMapping(value = "/user/listbehavior", method = RequestMethod.GET)
	public @ResponseBody Object getUserBehaviors(UserBehaviorQuery aQuery) {
		return service.getUserBehaviors(aQuery);
	}

	/***
	 * 获取某一天top多少
	 * 
	 * @param top:
	 *            int
	 * @param dateStr;
	 *            格式： yyyy-MM-dd，为空即为当天
	 * @param type:
	 *            模块名称
	 * @return
	 */
	@RequestMapping(value = "/user/topbehavior", method = RequestMethod.GET)
	public @ResponseBody Object getTopBehavior(UserBehaviorQuery aQuery) {
		return service.getTopBehavior(aQuery);
	}

	/***
	 * 获取某一天top多少
	 * 
	 * @param top:
	 *            int
	 * @param dateStr;
	 *            格式： yyyy-MM-dd，为空即为当天
	 * @param type:
	 *            模块名称
	 * @return
	 */
	@RequestMapping(value = "/user/allstat", method = RequestMethod.GET)
	public @ResponseBody Object getAllStat(UserBehaviorQuery aQuery) {
		Map<String, Object> map = service.getAllStat(aQuery);
		Map<String, Object> map1 = (Map<String, Object>) map.get("allstat");
		String teamurl = PropertiesUtil.getInstance().getProperty("teamurl");
		String cuturl = PropertiesUtil.getInstance().getProperty("cuturl");
		String result = "";
		try {
			result = HttpUtils.sendGet(teamurl + "countcreate?status=0");
			map1.put("tuancount", result);
			String states = "";
			result = HttpUtils.sendGet(cuturl + "count?statuses=0,1,2");
			map1.put("sharecount", result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		map.put("allstat", map1);
		return map;
	}

	/***
	 * 获取某一天top多少
	 * 
	 * @param top:
	 *            int
	 * @param dateStr;
	 *            格式： yyyy-MM-dd，为空即为当天
	 * @param type:
	 *            模块名称
	 * @return
	 */
	@RequestMapping(value = "/user/wx/stat", method = RequestMethod.GET)
	public @ResponseBody Object wxStat(UserBehaviorQuery aQuery) {
		String attentionurl = PropertiesUtil.getInstance().getProperty("wxserviceurl") + "/stat";
		;
		Map<String, Object> param = new HashMap<String, Object>();
		String currentDate = FormatDateTime.toShortTimeStringNoHour(new Date());
		param.put("first", currentDate + "访问统计");
		// param.setDate("2017-10-12 10:30");
		param.put("dateStr", FormatDateTime.toShortTimeString3(new Date()));
		param.put("company", "一虎一席茶席艺术商城");
		param.put("data", "详细统计数据请点击查看");
		param.put("remark", "");
		/*
		 * List<String> openids = new ArrayList<String>();
		 * openids.add("oimf-joPvA_sEwMtRSGq-md55-ts"); param.put("openids",
		 * openids);
		 */
		try {
			param.put("openids", WexinMsgByGroupService.getCustomerService());
		} catch (Exception e) {
			e.printStackTrace();
			List<String> ids = new ArrayList<String>();
			ids.add("oimf-joPvA_sEwMtRSGq-md55-ts");
			ids.add("oimf-jtehtEB7jtBtvrC_fRaG12s");
			ids.add("oimf-jgdYFoN9qu_zfTfB0t67hYA");
			ids.add("oimf-jrjcbSAtz59WOc_bkzbJHWA");
			ids.add("oimf-jsEWodjb3gTcMCenfmqxTqY");
			ids.add("oimf-jryWaQb6hT1pKV7QzB5sn_o");
			param.put("openids", ids);
		}

		param.put("url", "/#/stat?dateStr=" + currentDate);
		try {
			String result = HttpUtils.sendPostJson(attentionurl, JSON.toJSONString(param));
			log.info("stat.result: " + result);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return getResult(0, "");
	}

	@RequestMapping(value = "/user/addbehavior", method = RequestMethod.POST)
	public @ResponseBody Object addBehavior(@RequestBody UserBehavior ub) {
		Osslog.info("addBehavior: " + ub);
		return service.addUserBehavior(ub);
	}

	@RequestMapping(value = "/user/addviewstatis", method = RequestMethod.POST)
	public @ResponseBody Object addViewStatis(@RequestBody ViewPointStatis vps) {
		Osslog.info("ViewPointStatis: " + vps);
		return service.addViewStatis(vps);
	}

	@RequestMapping(value = "/user/listviewstatis", method = RequestMethod.GET)
	public @ResponseBody Object listViewStatis(ViewPointStatisQuery query) {
		Osslog.info("listviewstatis: " + query);
		return service.listViewStatis(query);
	}

	@RequestMapping(value = "/wechatlogin/add", method = RequestMethod.POST)
	public @ResponseBody Object addWechatStatis(@RequestBody WechatLoginStat vps) {
		Osslog.info("WechatLoginStat: " + vps);
		return service.addWechatStatis(vps);
	}

	@RequestMapping(value = "/wechatlogin/update", method = RequestMethod.POST)
	public @ResponseBody Object updateLogin(@RequestBody WechatLoginStat vps) {
		Osslog.info("updateLogin: " + vps);
		vps.setStatus(1);
		return service.updateWechatStatis(vps);
	}

	@RequestMapping(value = "/wechatlogin/stat", method = RequestMethod.GET)
	public @ResponseBody Object queryLoginstat(WechatLoginStatQuery vps) {
		Osslog.info("wechatloginstat: " + vps);
		if (vps.getStatus() < 0)
			vps.setStatus(0);
		return service.queryLoginstat(vps);
	}

	/***
	 * 获取朋友访问详情
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/user/friend/visit", method = RequestMethod.GET)
	public @ResponseBody Object getFriendVisitByUser(UsersQuery query) {
		Osslog.info("getFriendVisitByUser: " + query);
		return service.getFriendVisitByUser(query);
	}

	/***
	 * 获取朋友订单详情
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/user/friend/order", method = RequestMethod.GET)
	public @ResponseBody Object getFriendOrderByUser(UsersQuery query) {
		Osslog.info("getFriendOrderByUser: " + query);
		return service.getFriendOrderByUser(query);
	}
	
	@RequestMapping(value = "/redPack/list", method = RequestMethod.GET)
	public @ResponseBody Object getRedPackList(RedpackQuery query) {
		Osslog.info("getRedPackList: " + query);
		return service.getRedpacks(query);
	}
	
	/***
	 * 奖金提现
	 * @param vps
	 * @return
	 */
	@RequestMapping(value = "/sendRedPack", method = RequestMethod.POST)
	public @ResponseBody Object withdrawCash(@RequestBody RedPack redPack) {
		Osslog.info("cash: userId" + redPack.getUserId()+" payValue:"+redPack.getPayValue()+" actName:"+redPack.getActName()+" wish:"+redPack.getWish());
		ResponseVO res = new ResponseVO();
		if(redPack.getScene_id()==0){
			redPack.setWish("奖金提现");
			Wallet wallet = service.getWallet(redPack.getUserId());
			if(wallet==null){
				res.setResult(1);
				res.setMessage("fail");
				return res;
			}
			if(wallet.getRewardValue()<redPack.getPayValue()){
				res.setResult(1);
				res.setCode(DSConstants.ERROR_8002);
				res.setMessage("you don't have enouth reward.");
				return res;
			}
		}else if(redPack.getScene_id()==1){
			redPack.setWish("专用红包");
		}
		UserService as = new UserService();
		String userJson = as.getUserById(redPack.getUserId());
		User user = JSON.parseObject(userJson, User.class);
		if(StringUtils.isBlank(redPack.getOpenid()))
			redPack.setOpenid(user.getOpenid());
		double payValue = redPack.getPayValue();
		double value = 0;
		String postJson = "";
		int maxValue = DSConstants.WX_MAX_VALUE;
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("re_openid", redPack.getOpenid());
		map.put("wishing", redPack.getWish());
		map.put("act_name", redPack.getActName());
		map.put("remark", redPack.getRemark());
		map.put("send_name", redPack.getSendName());
		String url =PropertiesUtil.getInstance().getProperty("wxserviceurl")+"/wx/sendRedPack";
		Map<String,Object> resMap = new HashMap<String,Object>();
		if(payValue>maxValue){
			int times = (int)(Math.floor(payValue/maxValue));
			double last  = payValue%maxValue;
			last = InfoHelp.setTwoDecimal(last);
			Osslog.info("times: "+times+" last:"+last);
			for(int i=0;i<times;i++){
				map.put("total_amount", Math.round(maxValue*100));
				postJson = JSON.toJSONString(map);
				try {
					String result = HttpUtils.sendPostJson(url, postJson);
					Osslog.info("result: "+i+":"+result);
					JSONObject jo = JSON.parseObject(result);
					if(jo.getInteger("result")==0){
						value+=maxValue;
					}else{
						resMap.put("err_info_"+(i+1), jo);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			map.put("total_amount", Math.round(last*100));
			postJson = JSON.toJSONString(map);
			try {
				String result = HttpUtils.sendPostJson(url, postJson);
				Osslog.info("result: last"+result);
				JSONObject jo = JSON.parseObject(result);
				if(jo.getInteger("result")==0){
					value+=last;
				}else{
					resMap.put("err_info_last", jo);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			map.put("total_amount", Math.round(payValue*100));
			postJson = JSON.toJSONString(map);
			try {
				String result = HttpUtils.sendPostJson(url, postJson);
				Osslog.info("else.result:"+result);
				JSONObject jo = JSON.parseObject(result);
				if(jo.getInteger("result")==0){
					value = payValue;
				}else{
					res.setCode(1);
					resMap.put("err_info",jo);
					res.setData(resMap);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(value==0){
			return res;
		}
		Osslog.info("wallet.reduce.value: "+value);
		redPack.setPayValue(InfoHelp.setTwoDecimal(value));
		service.withdrawCash(redPack);
		return res;
	}

}
